package com.lxy.cxcyxmmsbackend.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxy.cxcyxmmsbackend.sys.entity.QxglUser;
import com.lxy.cxcyxmmsbackend.sys.entity.XmCxsq;
import com.lxy.cxcyxmmsbackend.sys.exceptionHandle.exce.NormalException;
import com.lxy.cxcyxmmsbackend.sys.req.PageReq;
import com.lxy.cxcyxmmsbackend.sys.res.Result;
import com.lxy.cxcyxmmsbackend.sys.service.CxcyXmService;
import com.lxy.cxcyxmmsbackend.sys.service.QxglUserService;
import com.lxy.cxcyxmmsbackend.sys.service.XmCxsqService;
import com.lxy.cxcyxmmsbackend.sys.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 撤销申请
 *
 * @author 刘新颖
 * @since 2024-01-07
 */
@Api(tags = "项目撤销申请")
@RestController
@RequestMapping("/xmCxsq")
public class XmCxsqController {

    @Autowired
    XmCxsqService xmCxsqService;

    @Resource
    CxcyXmService cxcyXmService;

    @Resource
    QxglUserService qxglUserService;


    @ApiOperation("查询项目撤销申请")
    @PostMapping("/queryXmCxsq")
    @Transactional
    public Result queryCxcyJhsByBh(@RequestBody PageReq pageReq) {
        Integer pageNo = pageReq.getCurrentPage();
        Integer pageSize = pageReq.getPageSize();
        Page<XmCxsq> pages = new Page<>(pageReq.getCurrentPage(), pageReq.getPageSize());
        QueryWrapper<XmCxsq> wrapper = new QueryWrapper<>();
        String xmmc = pageReq.getKeyWord().get("xmmc");
        String cxsqZt = pageReq.getKeyWord().get("cxsqZt");
        String xmBh = pageReq.getKeyWord().get("xmBh");
        if (xmBh != null && !"".equals(xmBh)) {
            wrapper.lambda().eq(XmCxsq::getXmBh, xmBh);
        }
        //项目名称
        if (xmmc != null && !"".equals(xmmc)) {
            wrapper.lambda().eq(XmCxsq::getXmMc, xmmc);
        }

        //项目状态
        if (cxsqZt != null && !"".equals(cxsqZt)) {
            wrapper.lambda().eq(XmCxsq::getCxsqZt, cxsqZt);
        }

        wrapper.orderByAsc("CXSQ_ZT");

        IPage<XmCxsq> page = xmCxsqService.page(pages, wrapper);

        HashMap<Object, Object> map = new HashMap<>();

        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        List<XmCxsq> records = page.getRecords();

        map.put("rows", records);
        map.put("total", page.getTotal());
        map.put("pageNums", (int) Math.ceil((double) page.getTotal() / pageSize));

        return Result.success("查询项目撤销申请列表成功", map);
    }

    @ApiOperation("保存项目撤销申请")
    @PostMapping("/saveXmCxsq")
    @Transactional
    public Result saveXmCxsq(@RequestBody XmCxsq xmCxsq, HttpServletRequest request) {
        String cxsqBh = xmCxsq.getCxsqBh();
        if (cxsqBh == null || "".equals(cxsqBh)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            Date date = null;
            try {
                date = sdf.parse(xmCxsq.getCxsqTcrq());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = outputFormat.format(date);
            xmCxsq.setCxsqTcrq(formattedDate);
            String userBh = request.getHeader("userBh");
            QxglUser user = qxglUserService.getById(userBh);
            xmCxsq.setCxsqBh(UUIDUtil.getUUID8("", 8));
            xmCxsq.setCxsqFzrbh(userBh);
            xmCxsq.setCxsqFzrmc(user.getUserMc());
            xmCxsq.setCxsqZt("0");
            QueryWrapper<XmCxsq> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(XmCxsq::getXmBh, xmCxsq.getXmBh());
            List<XmCxsq> list = xmCxsqService.list(queryWrapper);
            if (list != null && list.size() > 0) {
                throw new NormalException("该项目已经存在撤销申请，请等待项目管理员检查后审批！");
            }
            boolean save = xmCxsqService.save(xmCxsq);
            if (!save) {
                throw new NormalException("新增项目撤销申请失败");
            }
        }else {
            boolean save = xmCxsqService.updateById(xmCxsq);
            if (!save) {
                throw new NormalException("修改项目撤销申请失败");
            }
        }

        return Result.success("保存项目撤销申请成功", xmCxsq);
    }

    @ApiOperation("审批项目撤销申请")
    @PostMapping("/approvalXmCxsq")
    @Transactional
    public Result approvalXmCxsq(@RequestBody XmCxsq xmCxsq, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);
        xmCxsq.setCxsqSprbh(userBh);
        xmCxsq.setCxsqSprmc(user.getUserMc());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        xmCxsq.setCxsqSpsj(format.format(new Date(System.currentTimeMillis())));
        boolean save = xmCxsqService.updateById(xmCxsq);
        if (!save) {
            throw new NormalException("审批项目撤销申请失败");
        }
        return Result.success("审批项目撤销申请成功", xmCxsq);
    }

    @ApiOperation("查询项目撤销申请详情")
    @PostMapping("/getXmCxsqDetail/{bh}")
    @Transactional
    public Result getXmCxsqDetail(@PathVariable("bh") String bh) {
        QueryWrapper<XmCxsq> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(XmCxsq::getXmBh,bh);
        XmCxsq byId = xmCxsqService.getOne(queryWrapper);
        if (byId == null) {
            throw new NormalException("查询项目撤销申请详情失败");
        }
        return Result.success("查询项目撤销申请详情成功", byId);
    }

    @ApiOperation("删除项目撤销申请")
    @PostMapping("/removeXmCxsq/{bh}")
    @Transactional
    public Result removeXmCxsq(@PathVariable("bh") String bh) {
        boolean remove = xmCxsqService.removeById(bh);
        if (!remove) {
            throw new NormalException("删除项目撤销申请失败");
        }
        return Result.success("删除项目撤销申请成功", null);
    }

}

